<template>
  <splitpanes class="default-theme" style="height: auto">
    <pane :min-size="split.minWidth" :size="split.minWidth">
      <a-card
        @contextDictionary.prevent
        size="small"
        class="eip-admin-card-small"
      >
        <div slot="title">
          <a-input-search
            v-model="organization.key"
            :allowClear="true"
            placeholder="名称/拼音模糊搜索"
            @change="organizationSearch"
          />
        </div>
        <a-spin
          :spinning="organization.spinning"
          :delay="0"
          :style="organization.style"
        >
          <div>
            <a-directory-tree
              v-if="!organization.spinning"
              :expandAction="false"
              :defaultExpandedKeys="[
                organization.data.length > 0 ? organization.data[0].key : '',
              ]"
              :tree-data="organization.data"
              :icon="organizationIcon"
              @select="organizationSelect"
            ></a-directory-tree>
          </div>
        </a-spin>
      </a-card>
    </pane>
    <pane min-size="50">
      <vxe-grid v-bind="grid" ref="xGrid">
        <template #toolbar_buttons>
          <eip-toolbar
            @del="del"
            @update="update"
            @add="add"
            @detail="userDetail"
            @resetpassword="resetPassword"
            @downTemplate="downTemplate"
            @dataImport="dataImport"
            @onload="toolbarOnload"
            @leader="userLeader"
            @userExport="userExport"
          ></eip-toolbar>
        </template>
        <template #toolbar_tools> </template>
        <template #loading>
          <a-spin></a-spin>
        </template>
        <template #empty>
          <eip-empty />
        </template>
        <template #checkboxHeader="{ checked, indeterminate }">
          <span @click.stop="$refs.xGrid.toggleAllCheckboxRow()">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>
        <template #checkbox="{ row, checked, indeterminate }">
          <span @click.stop="$refs.xGrid.toggleCheckboxRow(row)">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>
        <template #isFreeze="{ row }">
          <a-switch :checked="row.isFreeze" @change="isFreezeChange(row)" />
        </template>
        <template #role="{ row }">
          <a-tag
            color="#108ee9"
            v-for="(item, index) in convertRole(row.role)"
            :key="index"
            >{{ item }}</a-tag
          >
        </template>
        <template #headImage="{ row }">
          <div class="flex justify-start align-center">
            <vxe-image
              :src="row.headImage"
              show-preview
              show-download-button
              style="width: 32px; height: 32px; border-radius: 50%"
            ></vxe-image>
            <label class="margin-left-xs"> {{ row.name }}</label>
          </div>
        </template>
        <template #operate="{ row }">
          <a-tooltip
            @click="tableUpdateRow(row)"
            title="编辑"
            v-if="visible.update"
          >
            <label class="text-eip eip-cursor-pointer">编辑</label>
          </a-tooltip>
          <a-divider type="vertical" v-if="visible.update" />
          <a-tooltip title="删除" v-if="visible.del" @click="tableDelRow(row)">
            <label class="text-red eip-cursor-pointer">删除</label>
          </a-tooltip>
        </template>
      </vxe-grid>
    </pane>

    <edit
      ref="edit"
      v-if="edit.visible"
      :visible.sync="edit.visible"
      :data="organization.data"
      :title="edit.title"
      :userId="edit.userId"
      @save="operateStatus"
    ></edit>

    <detail
      ref="detail"
      v-if="detail.visible"
      :visible.sync="detail.visible"
      :userId="detail.userId"
      :title="detail.title"
      :privilegeMaster="privilege.master"
      :privilegeMasterValue="privilege.masterValue"
    ></detail>

    <a-modal
      @cancel="upload.visible = false"
      title="导入错误"
      :visible="upload.visible"
      :footer="null"
      v-drag
    >
      <div v-html="upload.msg"></div>
    </a-modal>

    <reset-password
      ref="resetPassword"
      v-if="toolbar.resetPassword.visible"
      :visible.sync="toolbar.resetPassword.visible"
      :title="toolbar.resetPassword.title"
      :userId="toolbar.resetPassword.userId"
    ></reset-password>

    <leader
      ref="leader"
      v-if="leader.visible"
      :visible.sync="leader.visible"
      :data="organization.data"
      :title="leader.title"
      :userId="leader.userId"
      @save="perateStatusLeader"
    ></leader>
  </splitpanes>
</template>

<script>
import {
  organizationQuery,
  query,
  del,
  isFreeze,
  downImportTemplate,
  systemUserImport,
  systemUserExport,
  systemUserImportMobile,
} from "@/services/system/user/list";
import edit from "./edit";
import leader from "./leader";
import detail from "./detail";
import resetPassword from "./resetPassword";
import { selectTableRow, deleteConfirm } from "@/utils/util";

import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
export default {
  components: {
    edit,
    detail,
    resetPassword,
    leader,
    Splitpanes,
    Pane,
  },
  data() {
    return {
      split: {
        minWidth: (250 / window.innerWidth) * 100,
      },
      organization: {
        style: {
          overflow: "auto",
          height: this.eipTableHeight() - 60 + "px",
        },
        key: null,
        original: [],
        data: [],
        spinning: true,
        right: {
          item: null,
          style: "",
        },
      },
      upload: {
        file: null,
        visible: false,
        msg: "",
      },
      grid: {
        id: "user",
        loading: true,
        height: this.eipTableHeight(),
        pagerConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        sortConfig: {
          trigger: "cell",
          defaultSort: { field: "orderNo", order: "asc" },
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        customConfig: {
          mode: "popup",
        },
        columns: [
          {
            type: "checkbox",
            width: 50,
            slots: {
              checkbox: "checkbox",
              header: "checkboxHeader",
            },
            fixed: "left",
            align: "center",
          },
          { type: "seq", width: 60, fixed: "left" },
          {
            field: "code",
            title: "登录名",
            width: 120,
            sortable: true,
            showOverflow: "ellipsis",
            fixed: "left",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "name",
            title: "姓名",
            width: 120,
            sortable: true,
            showOverflow: "ellipsis",
            fixed: "left",
            slots: {
              default: "headImage",
            },
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "role",
            title: "角色",
            width: 120,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            slots: {
              default: "role",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "sonUserNumber",
            title: "下级数",
            width: 130,
            align: "center",
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "number",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "leaderUserNumber",
            title: "上级数",
            width: 130,
            align: "center",
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "number",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "parentIdsName",
            title: "归属组织",
            width: 220,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "userOrganizationNames",
            title: "关联组织",
            width: 140,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "orderNo",
            title: "排序号",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "number",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "mobile",
            title: "手机号码",
            width: 140,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "email",
            title: "邮箱",
            width: 120,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "otherContactInformation",
            title: "其他联系信息",
            width: 160,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "lastVisitTime",
            title: "最后登录时间",
            width: 160,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "isFreeze",
            title: "禁用",
            width: 120,
            sortable: true,
            showOverflow: true,
            slots: {
              default: "isFreeze",
            },
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "switch",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [
                    {
                      value: 1,
                      label: "已禁用",
                      checked: false,
                      color: "red",
                    },
                    {
                      value: 0,
                      label: "未禁用",
                      checked: false,
                      color: "#1890ff",
                    },
                  ],
                },
              },
            ],
          },
          {
            field: "remark",
            title: "备注",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },

          {
            field: "createUserName",
            title: "创建人",
            width: 150,
            sortable: true,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "createTime",
            title: "创建时间",
            width: 150,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "updateUserName",
            title: "修改人",
            width: 150,
            sortable: true,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "updateTime",
            title: "修改时间",
            width: 150,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            title: "操作",
            width: 100,
            align: "center",
            fixed: "right",
            slots: {
              default: "operate",
            },
          },
        ],

        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          props: {
            result: "data", // 配置响应结果列表字段
            total: "total", // 配置响应结果总页数字段
          },
          ajax: {
            query: ({ page, sorts, filters }) => {
              return new Promise((resolve) => {
                const firstSort = sorts[0];
                query({
                  filters: this.eipTableFilter(filters),
                  current: page.currentPage,
                  size: page.pageSize,
                  id: this.grid.extend.id,
                  sort: this.eipGridSort(sorts),
                  privilegeMasterValue: null,
                  privilegeMaster: this.eipPrivilegeMaster.organization,
                }).then((result) => {
                  if (result.code == this.eipResultCode.success) {
                    resolve(result);
                  }
                  this.grid.loading = false;
                });
              });
            },
          },
        },
        data: [],
        extend: {
          id: null,
        },
      },

      edit: {
        visible: false,
        userId: "",
        title: "",
        data: [],
      },
      leader: {
        visible: false,
        userId: "",
        title: "",
        data: [],
      },
      detail: {
        visible: false,
        userId: "",
        title: "",
      },
      visible: {
        update: false,
        del: false,
      },

      privilege: {
        master: this.eipPrivilegeMaster.user,
        masterValue: null,
      },
      toolbar: {
        resetPassword: {
          visible: false,
          title: null,
          userId: "",
        },
      },
    };
  },
  created() {
    this.organizationInit();
  },
  methods: {
    /**
     *
     * @param {*} e
     */
    organizationSearch(e) {
      var that = this;
      this.organization.data = that.$utils.clone(
        this.organization.original,
        true
      );
      this.organization.data = that.$utils.searchTree(
        this.organization.data,
        (item) => {
          if (that.organization.key) {
            var titlePinyin = pinyin.convert(item.title).toLowerCase();
            if (
              item.title
                .toLowerCase()
                .includes(that.organization.key.toLowerCase())
            ) {
              return true;
            } else if (
              titlePinyin.includes(that.organization.key.toLowerCase())
            ) {
              return true;
            } else {
              return false;
            }
          } else {
            return true;
          }
        },
        { children: "children" }
      );
    },
    /**
     *冻结
     */
    isFreezeChange(row) {
      if (this.visible.update) {
        let that = this;
        isFreeze({ id: row.userId }).then((result) => {
          that.$message.destroy();
          if (result.code == that.eipResultCode.success) {
            that.userInit();
            that.$message.success(result.msg);
          } else {
            that.$message.error(result.msg);
          }
        });
      }
    },
    /**
     * 菜单树
     */
    organizationInit() {
      let that = this;
      that.organization.spinning = true;
      organizationQuery().then((result) => {
        that.organization.data = result.data;
        that.organization.original = result.data;
        that.organization.spinning = false;
        that.organizationSearch();
      });
    },

    /**
     * 树图标
     */
    organizationIcon(props) {
      const { expanded } = props;
      if (props.children.length == 0) {
        return <a-icon type="file" />;
      }
      return <a-icon type={expanded ? "folder-open" : "folder"} />;
    },

    /**
     * 树选中
     */
    organizationSelect(electedKeys, e) {
      this.grid.extend.privilegeMasterValue = electedKeys[0];
      this.grid.extend.current = 1;
      this.userInit();
    },

    /**
     * 列表数据
     */
    userInit() {
      this.$refs.xGrid.commitProxy("query");
    },

    /**
     * 权限按钮加载完毕
     */
    toolbarOnload(buttons) {
      this.visible.add = buttons.filter((f) => f.method == "add").length > 0;
      this.visible.update =
        buttons.filter((f) => f.method == "update").length > 0;
      this.visible.del = buttons.filter((f) => f.method == "del").length > 0;
    },

    /**
     * 树更新
     */
    tableUpdateRow(row) {
      this.edit.userId = row.userId;
      this.edit.title = "用户编辑-" + row.name;
      this.edit.visible = true;
    },

    /**
     * 删除
     */
    tableDelRow(row) {
      let that = this;
      deleteConfirm(
        "用户【" + row.name + "】" + that.eipMsg.delete,
        function () {
          that.$loading.show({ text: that.eipMsg.delloading });
          del({ id: row.userId }).then((result) => {
            that.$loading.hide();
            if (result.code == that.eipResultCode.success) {
              that.userInit();
              that.$message.success(result.msg);
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 新增
     */
    add() {
      this.edit.title = "新增用户";
      this.edit.userId = null;
      this.edit.visible = true;
    },

    /**
     * 修改
     */
    update() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (row) {
          that.edit.userId = row.userId;
          that.edit.title = "编辑用户-" + row.name;
          that.edit.visible = true;
        },
        that
      );
    },

    /**
     * 设置领导
     */
    userLeader() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (row) {
          that.leader.userId = row.userId;
          that.leader.title = "领导设置-" + row.name;
          that.leader.visible = true;
        },
        that
      );
    },
    /**
     * 保存领导
     */
    perateStatusLeader() {},

    /**
     * 用户详情
     */
    userDetail() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (row) {
          that.detail.userId = row.userId;
          that.detail.title = "用户详情-" + row.name;
          that.detail.visible = true;
        },
        that
      );
    },

    /**
     * 删除
     */
    del() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (rows) {
          //提示是否删除
          deleteConfirm(
            that.eipMsg.delete,
            function () {
              //加载提示
              that.$loading.show({ text: that.eipMsg.delloading });
              let ids = that.$utils.map(rows, (item) => item.userId);
              del({ id: ids.join(",") }).then((result) => {
                that.$loading.hide();
                if (result.code == that.eipResultCode.success) {
                  that.userInit();
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            },
            that
          );
        },
        that,
        false
      );
    },

    /**
     * 提示状态信息
     * @param {*} result
     */
    operateStatus(result) {
      if (result.code === this.eipResultCode.success) {
        this.userInit();
      }
    },

    /**
     * 下载导入模版
     */
    downTemplate() {
      downImportTemplate();
    },

    /**
     *导入
     */
    dataImport(file) {
      let that = this;
      const formData = new FormData();
      formData.append("Files", file.file);
      that.$message.loading({
        content: "导入中...",
        duration: 0,
      });
      systemUserImport(formData)
        .then((result) => {
          that.$message.destroy();
          if (result.code == that.eipResultCode.success) {
            that.$message.success(result.msg);
            that.userInit();
          } else {
            var msg = [];
            try {
              var datas = JSON.parse(result.msg);
              datas.forEach((item) => {
                var m = "";
                m += "第" + item.RowIndex + "行，";
                for (let key in item.FieldErrors) {
                  m += item.FieldErrors[key] + ",";
                }
                msg.push(m);
              });
              that.upload.msg = msg.join("<br/>");
              that.upload.visible = true;
            } catch (error) {
              result.data.forEach((item) => {
                msg.push(item);
              });
              that.upload.msg = msg.join("<br/>");
              that.upload.visible = true;
            }
          }
        })
        .catch(() => {
          that.$message.destroy();
          that.$message.error("上传出错");
        });
    },

    /**
     * 用户导出
     */
    userExport() {
      let that = this;
      systemUserExport(that.grid.extend).then((result) => {
        that.$message.success("导出成功");
      });
    },
    /**
     *
     * @param role
     */
    convertRole(role) {
      return role.split(",");
    },
    /**
     * 重置密码
     */
    resetPassword() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (row) {
          that.toolbar.resetPassword.visible = true;
          that.toolbar.resetPassword.title = "重置密码-" + row.name;
          that.toolbar.resetPassword.userId = row.userId;
        },
        that
      );
    },
  },
};
</script>

<style lang="less" scoped>
.eip-admin-card-small .ant-form-item {
  margin-bottom: 0;
}

.ant-card-body {
  padding: 10px !important;
}
</style>
